﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyVoteMVC.Domain;
using MyVoteMVC.BackstageManagement.Controllers;
using MyVoteMVC.Service;
using MyVoteMVC.Common;
using MyVoteMVC.Data;


namespace MyVoteMVC.BackstageManagement.Views
{
    public interface IActivityLotteryView
    {
        void GetActivityListComplete(IList<VT_Activities> list);
        void GetItemmListComplete(IList<VT_Items> list);
        void GetUsersListComplete(string[] userIDs, string[] ticketIDs, int[] itemCounts, int iEndCount);
        void GetUserInfoComplete(VT_Users v_User);
        void ShowDetailComplete(string[] strItems, string strUseName);
        void DeleteLotteriesComplete(bool bl);
        void GetActivityLotteryComplete(IList<VT_Lotteries> list);
        void AddActivityLotteriesComplete(bool bl);
    }

    public partial class ActivityLottery : Form, IActivityLotteryView
    {
        string strActivityID = "";
        private IActivityLotteryControl controller;
        IAuserService usersService;
        ILotteriesService lotteriesService;
        public ActivityLottery()
        {
            InitializeComponent();
            controller = new ActivityLotteryControl(this);
            usersService = Factory.GetInstance<IAuserService>();
            lotteriesService = Factory.GetInstance<ILotteriesService>();
        }

        private void ActivityLottery_Load(object sender, EventArgs e)
        {
            controller.GetActivityList();
        }
        public void GetActivityLotteryComplete(IList<VT_Lotteries> list)
        {
            gvlotteryUser.DataSource = null;
            gvlotteryUser.DataSource = list;
            if (gvlotteryUser.DataSource != null)
            {
                for (int i = 0; i < gvlotteryUser.ColumnCount; i++)
                {
                    gvlotteryUser.Columns[i].Visible = false;
                } 
                gvlotteryUser.Columns["Lottery_Level"].Visible = true;
                gvlotteryUser.Columns["Lottery_Level"].HeaderText = "中奖名次";
                gvlotteryUser.Columns["Lottery_Level"].DisplayIndex = 0;
                gvlotteryUser.Columns["Lottery_Level"].Width = 100;
                gvlotteryUser.Columns["User_Email"].Visible = true;
                gvlotteryUser.Columns["User_Email"].HeaderText = "中奖用户邮箱";
                gvlotteryUser.Columns["User_Email"].DisplayIndex = 1;
                gvlotteryUser.Columns["User_Email"].Width = 150;
                gvlotteryUser.Columns["Created_Date"].Visible = true;
                gvlotteryUser.Columns["Created_Date"].HeaderText = "中奖时间";
                gvlotteryUser.Columns["Created_Date"].DisplayIndex = 2;
                gvlotteryUser.Columns["Created_Date"].Width = 100;
            }   
        }
        public void GetActivityListComplete(IList<VT_Activities> list)
        {
            gvActivity.DataSource = list;
            if (gvActivity.DataSource != null)
            {
                for (int i = 0; i < gvActivity.ColumnCount; i++)
                {
                    gvActivity.Columns[i].Visible = false;
                }
                gvActivity.Columns["Activity_ID"].Visible = true;
                gvActivity.Columns["Activity_ID"].HeaderText = "项目编号";
                gvActivity.Columns["Activity_Title"].Visible = true;
                gvActivity.Columns["Activity_Title"].HeaderText = "项目标题";
            }
        }
        public void GetUserInfoComplete(VT_Users v_User)
        {
            return;
        }
        public void DeleteLotteriesComplete(bool bl)
        {
            return;
        }
        public void GetUsersListComplete(string[] userIDs,string[] ticketIDs, int[] itemCounts, int iEndCount)
        {
            //初始化所有的用户数量排名
            lvUsers.Items.Clear();
            int i = 0;
            for (i = 0; i < userIDs.Length; i++)
            {
                VT_Users v_User = usersService.GetUserByID(userIDs[i]);
                if (v_User != null)
                {
                    ListViewItem lvItem = new ListViewItem();
                    lvItem.Text = v_User.User_Name;
                    lvItem.SubItems.Add(itemCounts[i].ToString());
                    lvItem.SubItems.Add(v_User.User_ID);
                    lvItem.SubItems.Add(strActivityID);
                    lvUsers.Items.Add(lvItem);
                }
            }
            //找出前N名的排名
            lvUserLottery.Items.Clear();
            for (i = 0; i < iEndCount; i++)
            {
                VT_Users v_User = usersService.GetUserByID(userIDs[i]);
                if (v_User != null)
                {
                    ListViewItem lvItem = new ListViewItem();
                    lvItem.Text = v_User.User_Name;
                    lvItem.SubItems.Add(itemCounts[i].ToString());
                    lvItem.SubItems.Add(v_User.User_ID);
                    lvItem.SubItems.Add(strActivityID);
                    lvUserLottery.Items.Add(lvItem);
                }
            }

        }

        public void GetItemmListComplete(IList<VT_Items> list)
        {
            int iShow = 0;
            int iTure = 0;
            int MaxCount = 0;
            lvItemmList.Items.Clear();
            foreach (VT_Items vs in list)
            {
                int iOnLine = 0;
                int iOffLine = 0;
                int iAll = 0;
                ListViewItem lvItem = new ListViewItem();
                if (vs.Online_Count != null) iOnLine = Int32.Parse(vs.Online_Count.ToString());
                if (vs.Offline_Count != null) iOffLine = Int32.Parse(vs.Offline_Count.ToString());
                iAll = iOnLine + iOffLine;
                if (iAll == MaxCount)
                {
                    iTure = iTure + 1;
                }
                else
                {
                    MaxCount = iAll;
                    iTure = iTure + 1;
                    iShow = iTure;
                }
                lvItem.Text = iShow.ToString();
                lvItem.SubItems.Add(vs.Item_Title);
                lvItem.SubItems.Add(iOnLine.ToString());
                lvItem.SubItems.Add(iOffLine.ToString());
                lvItem.SubItems.Add(iAll.ToString());
                lvItem.SubItems.Add(vs.Item_ID);
                lvItemmList.Items.Add(lvItem);
            }
        }
        private void gvActivity_SelectionChanged(object sender, EventArgs e)
        {
            if (gvActivity.SelectedRows.Count > 0 && gvActivity.SelectedRows[0].DataBoundItem != null)
            {
                VT_Activities v_Activitise = gvActivity.SelectedRows[0].DataBoundItem as VT_Activities;
                //获取该活动的选项的票数
                controller.GetItemmList(v_Activitise.Activity_ID);
                controller.GetActivityLotteryList(v_Activitise.Activity_ID);
                strActivityID = v_Activitise.Activity_ID;
                lvDetail.Items.Clear();
                lvUserLottery.Items.Clear();
                lvUsers.Items.Clear();
            }
            else strActivityID = "";
           
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
               
                if (string.IsNullOrEmpty(txtMatchItemm.Text.Trim()) || string.IsNullOrEmpty(txtMatchUser.Text.Trim()))
                {
                    MessageBox.Show("匹配的选项和匹配用户数不能为空！");
                    return;
                }
                int iMatchItemms = int.Parse(txtMatchItemm.Text.Trim());
                int iMatchUsers = int.Parse(txtMatchUser.Text.Trim());
                if (iMatchItemms <= 0 || iMatchUsers <= 0)
                {
                    MessageBox.Show("匹配的参数必须大于0");
                }
                if (lvItemmList.Items.Count < iMatchItemms)
                {
                    MessageBox.Show("匹配选项超出范围！");
                    return;
                }
                if (string.IsNullOrEmpty(strActivityID))
                {
                    MessageBox.Show("请选择一个活动！");
                }

                string strItemIDs = "";
                for (int i = 0; i < lvItemmList.Items.Count; i++)
                {
                    int iNumber = int.Parse(lvItemmList.Items[i].SubItems[0].Text.ToString());
                    if (iNumber <= iMatchItemms)
                        strItemIDs += lvItemmList.Items[i].SubItems[5].Text.ToString() + ";";
                }
                if (!string.IsNullOrEmpty(strItemIDs)) strItemIDs = strItemIDs.Substring(0, strItemIDs.Length - 1);

                controller.GetUsersList(strActivityID, strItemIDs, iMatchUsers);

                // 找出集合
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void ShowDetailComplete(string[] strItems, string strUseName)
        {
            lvDetail.Items.Clear();
            for (int i = 0; i < strItems.Length; i++)
            {
                ListViewItem lvItem = new ListViewItem();
                lvItem.Text = (i + 1).ToString();
                lvItem.SubItems.Add(strUseName);
                lvItem.SubItems.Add(strItems[i]);
                lvDetail.Items.Add(lvItem);              
            }
        }

        private void lvUsers_Click(object sender, EventArgs e)
        {
            if (this.lvUsers.SelectedItems != null)
            {
                controller.ShowDetail(lvUsers.SelectedItems[0].SubItems[3].Text.ToString(), lvUsers.SelectedItems[0].SubItems[2].Text.ToString(), lvUsers.SelectedItems[0].SubItems[0].Text.ToString());

            }
        }

        private void lvUserLottery_Click(object sender, EventArgs e)
        {
            if (this.lvUserLottery.SelectedItems != null)
            {
                controller.ShowDetail(lvUserLottery.SelectedItems[0].SubItems[3].Text.ToString(), lvUserLottery.SelectedItems[0].SubItems[2].Text.ToString(), lvUserLottery.SelectedItems[0].SubItems[0].Text.ToString());

            }
        }

        public void AddActivityLotteriesComplete(bool bl)
        {
            return;
        }
        private void btnLottery_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtLotteryNumber.Text.Trim()))
                {
                    MessageBox.Show("中奖人数不能为空");
                    return;
                }
                int iLNumber = Int32.Parse(txtLotteryNumber.Text.Trim());
                if (iLNumber <= 0)
                {
                    MessageBox.Show("中奖人数必须大于0");
                    return;
                }
                if (lvUserLottery.Items.Count <=0)
                {
                    MessageBox.Show("请先匹配参与抽奖用户！");
                    return;
                }
                if (lvUserLottery.Items.Count < iLNumber)
                {
                    MessageBox.Show("参与抽奖用户小于中奖人数");
                    return;
                }
                btnLottery.Enabled = false;
                if (rdnMax.Checked == true)
                {
                    LotteryProgram(lvUserLottery, Int32.Parse(txtLotteryNumber.Text.Trim()),"0");
                }
                else if (rdnRandom.Checked == true)
                {
                    LotteryProgram(lvUserLottery, Int32.Parse(txtLotteryNumber.Text.Trim()),"1");
                }
                if (gvActivity.SelectedRows.Count > 0 && gvActivity.SelectedRows[0].DataBoundItem != null)
                {
                    VT_Activities v_Activitise = gvActivity.SelectedRows[0].DataBoundItem as VT_Activities;
                    //获取该活动的选项的票数
                    controller.GetActivityLotteryList(v_Activitise.Activity_ID);                 
                }
                btnLottery.Enabled = true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
                btnLottery.Enabled = true;
            }
        }
        private void LotteryProgram(ListView dv, int number,string strType)
        {
            if (dv == null)
            {
                MessageBox.Show("没有数据！");
                return;
            }

            int iRan = lotteriesService.GetActivityLotteriesCount(dv.Items[0].SubItems[3].Text.ToString()) + 1;

            // 按照最大来抽
            if (strType == "0")
            {
                txtResult.Text = "中奖用户为以下：";
                for (int i = 0; i < number; i++)
                {
                    txtResult.Text += "\r\n" + "第" + iRan.ToString() + "名：" + dv.Items[i].SubItems[0].Text.ToString();
                    //插入中奖表记录
                    controller.AddActivityLotteries(dv.Items[i].SubItems[3].Text.ToString(), dv.Items[i].SubItems[2].Text.ToString(), iRan);
                    iRan++;
                }
            }
            else
            {
                int[] numberlist = new int[number];
                for (int i = 0; i < number; i++)
                {
                    numberlist[i] = -1;
                }
                for (int i = 0; i < number; i++)
                {
                    Random rnd = new Random();
                    int rndNum = rnd.Next(0, dv.Items.Count);//- 1
                    bool isRepeat = false;
                    for (int j = 0; j < numberlist.Length; j++)
                    {
                        if (numberlist[j] == rndNum)
                        {
                            isRepeat = true;
                            break;
                        }
                    }
                    if (isRepeat == true)
                    {
                        //重复则重新再抽查一次
                        i = i - 1;
                    }
                    else numberlist[i] = rndNum;
                }

                //插入中奖表记录 
                txtResult.Text = "中奖用户为以下：";
                for (int i = 0; i < numberlist.Length; i++)
                {
                    //插入中奖表记录 
                    txtResult.Text += "\r\n" + "第" + iRan.ToString() + "名：" + dv.Items[numberlist[i]].SubItems[0].Text.ToString();
                    controller.AddActivityLotteries(dv.Items[numberlist[i]].SubItems[3].Text.ToString(), dv.Items[numberlist[i]].SubItems[2].Text.ToString(), iRan);
                    iRan++;
                }
            }
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (gvlotteryUser.SelectedRows.Count > 0)
            {
                btnDel.Enabled = false;
                for (int i = 0; i < gvlotteryUser.SelectedRows.Count; i++)
                {
                    VT_Lotteries v_Lotteries = gvlotteryUser.SelectedRows[i].DataBoundItem as VT_Lotteries;
                    controller.DeleteLotteries(v_Lotteries.Lottery_ID);
                }
                gvActivity_SelectionChanged(null, null);
                MessageBox.Show("删除成功");
                btnDel.Enabled = true;
            }
            else
            {
                MessageBox.Show("请选中要删除的数据！");
            }
        }

        private void gvlotteryUser_SelectionChanged(object sender, EventArgs e)
        {
            if (gvlotteryUser.SelectedRows.Count > 0 && gvlotteryUser.SelectedRows[0].DataBoundItem != null)
            {
                VT_Lotteries v_Lotteries = gvlotteryUser.SelectedRows[0].DataBoundItem as VT_Lotteries;
                VT_Users v_User= usersService.GetUserByEmail(v_Lotteries.User_Email);
                controller.ShowDetail(v_Lotteries.Activity_ID, v_User.User_ID,v_User.User_Name);
            }
            
        }
    }
}
